#!/usr/bin/env python

import sys
import xmlrpclib
from optparse import OptionParser

from autobbotd.buildbot import CTBuildBot
from autobbotd.bbconfig import *

if __name__ == "__main__":
    parser = OptionParser()
    opts, args = parser.parse_args()

    daemon = CTBuildBot('/tmp/autobbotd.pid')
    if len(args) == 1:
        if 'start' == args[0]:
            daemon.start()
        elif 'stop' == args[0]:
            try:
                xmlrpclib.ServerProxy("http://%s:%s" % ("localhost", LOCALPORT)).safeStop()
            except socket.error:
                print "Appears to already be stopped."
            daemon.stop()
        elif 'restart' == args[0]:
            xmlrpclib.ServerProxy("http://%s:%s" % ("localhost", LOCALPORT)).safeStop()
            daemon.restart()
        elif 'forcestop' == args[0]:
            daemon.stop()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|forcestop|restart" % args
        sys.exit(2)

